package cn.b.sky.mes.cm.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.cm.model.Operation;
import cn.b.sky.mes.cm.model.condition.OperationCondition;
import cn.b.sky.mes.cm.service.OperationService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;

/**
 * <strong>Title : OperationController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.platform.web.controller<br></strong>
 * <strong>Description : </strong>工序控制器<br> 
 * <strong>Create on : 2015-9-30 上午09:57:19<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */

@Controller
@RequestMapping(value = "/operation/*")
public class OperationController extends SecurityController {
  @Resource
  private OperationService operationService;

  @Resource
  ECodeService eCodeService;

  @RequestMapping(value = "operationList")
  public String operationList(Model model, @ModelAttribute("condition") OperationCondition operationCondition,
      String navTabId) {
    operationCondition.setSiteCode(this.getSiteCode());
    List<Operation> operations = operationService.selectOperationList(operationCondition);
    int count = operationService.getOperationCount(operationCondition);

    List<ECode> operationTypeECode = eCodeService.selectECodeList(ECodeEnums.OPERATIONTYPE.getCode(),
        SecurityContextUtil.getLanguageCode());

    operationCondition.setData(operations);
    operationCondition.setTotalCount(count);
    model.addAttribute("page", operationCondition);
    model.addAttribute("operationTypeECode", operationTypeECode);
    model.addAttribute(NAVTABID, navTabId);
    return "cm/operation/operation_list";
  }

  @RequestMapping(value = "addOperation")
  public String addOperation(String navTabId, Model model) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("pattern", "add");

    List<ECode> operationTypeECode = eCodeService.selectECodeList(ECodeEnums.OPERATIONTYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("operationTypeECode", operationTypeECode);
    return "cm/operation/operation_add";
  }

  @RequestMapping(value = "modifyOperation")
  public String modifyOperation(String navTabId, String id, Model model) {
    Operation operation = operationService.getOperation(id, getSiteCode());
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("operation", operation);
    model.addAttribute("pattern", "modify");
    List<ECode> operationTypeECode = eCodeService.selectECodeList(ECodeEnums.OPERATIONTYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("operationTypeECode", operationTypeECode);
    return "cm/operation/operation_add";

  }

  @RequestMapping(value = "viewOperation")
  public String viewOperation(String navTabId, String id, Model model) {

    Operation operation = operationService.getOperation(id, getSiteCode());
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("operation", operation);
    model.addAttribute("pattern", "read");
    List<ECode> operationTypeECode = eCodeService.selectECodeList(ECodeEnums.OPERATIONTYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("operationTypeECode", operationTypeECode);
    return "cm/operation/operation_add";

  }

  @RequestMapping(value = "validateOperationCode")
  @ResponseBody
  public boolean validateOperationCode(String operationCode, Model model) {
    if (!StringUtils.isBlank(operationCode)) {

      int count = operationService.getOperationExactCount(operationCode, getSiteCode());
      return count == 0;
    }
    return true;
  }

  @RequestMapping(value = "saveOperation")
  @ResponseBody
  public DWZResult saveOperation(Model model, String navTabId, String id, Operation operation,
      HttpServletRequest request) {
    if (operation == null) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }

    setCreateInfo(operation);
    if (StringUtils.isBlank(id)) {
      operation.setSiteCode(operation.getSiteCode());
      operationService.insertOperation(operation);
      String forwardUrl = getForwardUrl(request) + "/operation/operationList?navTabId=" + navTabId;
      return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), navTabId, null, forwardUrl, null);
    } else {
      operationService.updateOperation(operation);
      return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), navTabId, null, null, null);
    }
  }

  @RequestMapping("deleteOperation")
  @ResponseBody
  public DWZResult deleteOperation(Model model, String navTabId, String id, HttpServletRequest request) {

    String ids = request.getParameter("ids");
    if (StringUtils.isBlank(ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String[] operationCodes = ids.split(",");
    int len = operationCodes.length;
    if (len == 0) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    BatchJobReport[] reports = new BatchJobReport[len];
    boolean success = true;
    for (int i = 0; i < len; i++) {
      reports[i] = operationService.deleteOperations(operationCodes[i], getSiteCode());
      if (!reports[i].isSuccess()) {
        success = false;
      }
    }
    if (success) {
      //直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, Arrays.asList(reports));
    }

  }

  /**
   * 
   * <strong>Title : operationLookUp<br></strong>
   * <strong>Description : </strong>工序的查找带回<br> 
   * <strong>Create on : 2015-10-6 下午2:55:19<br></strong>
   * <p>
   * @param model
   * @param lookupType
   * @param operationCondition
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("operationLookUp")
  public String operationLookUp(Model model, String lookupType,
      @ModelAttribute("condition") OperationCondition operationCondition) {
    operationCondition.setSiteCode(this.getSiteCode());
    List<Operation> operations = operationService.selectOperationList(operationCondition);
    int count = operationService.getOperationCount(operationCondition);
    operationCondition.setData(operations);
    operationCondition.setTotalCount(count);
    List<ECode> operationTypeECode = eCodeService.selectECodeList(ECodeEnums.OPERATIONTYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    Map<String, String> map = new HashMap<String, String>();
    for (ECode ecode : operationTypeECode) {
      if (ecode != null && !StringUtils.isBlank(ecode.geteCode())) {
        map.put(ecode.geteCode(), ecode.geteCodeText());
      }
    }
    for (Operation operation : operations) {
      operation.setOperationTypeText(map.get(operation.getOperationTypeEcode()));
    }
    model.addAttribute("page", operationCondition);
    if (!StringUtils.isBlank(lookupType) && "radio".equals(lookupType)) {
      return "cm/operation/operation_lookup_radio"; //单选查找带回
    }
    return "cm/operation/operation_lookup";
  }

  /**
   * 
   * <strong>Title : operationSuggest<br></strong>
   * <strong>Description : </strong>工作下拉匹配<br> 
   * <strong>Create on : 2015-10-6 下午2:55:39<br></strong>
   * <p>
   * @param operationCondition
   * @return
   * Object
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("operationSuggest")
  @ResponseBody
  public Object operationSuggest(@ModelAttribute("condition") OperationCondition operationCondition) {
    operationCondition.setSiteCode(this.getSiteCode());
    List<Operation> operations = operationService.selectOperationSuggest(operationCondition);
    List<ECode> operationTypeECode = eCodeService.selectECodeList(ECodeEnums.OPERATIONTYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    Map<String, String> map = new HashMap<String, String>();
    for (ECode ecode : operationTypeECode) {
      if (ecode != null && !StringUtils.isBlank(ecode.geteCode())) {
        map.put(ecode.geteCode(), ecode.geteCodeText());
      }
    }
    for (Operation operation : operations) {
      operation.setOperationTypeText(map.get(operation.getOperationTypeEcode()));
    }
    return operations;
  }
  
  /**
   * 
   * <strong>Title : validateOperation<br></strong>
   * <strong>Description : </strong>查找带回控件校验工序是否存在<br> 
   * <strong>Create on : 2016-7-11 上午11:24:46<br></strong>
   * <p>
   * @param operationCode
   * @param model
   * @return
   * boolean
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "validateOperationLookUp")
  @ResponseBody
  public boolean validateOperationLookUp(String operationCode, Model model) {
    if (!StringUtils.isBlank(operationCode)) {

      int count = operationService.getOperationExactCount(operationCode, getSiteCode());
      return count != 0;
    }
    return false;
  }
}
